//*******************************************************************
//	created:	23:4:2011   21:38
//	filename: 	logmanager.cpp
//	author:		tiamo
//	purpose:	log manager
//*******************************************************************

#include "stdafx.h"
#include "logmanager.h"

namespace utils
{
	//
	// constructor
	//
	LogManager::LogManager()
	{
		mSyslog																= false;
		mLogLevel															= LevelWarning;
		memset(&mLastLogTime, 0, sizeof(mLastLogTime));
	}

	//
	// destructor
	//
	LogManager::~LogManager()
	{
	#ifndef WIN32
		if(mSyslog)
			closelog();
	#endif
	}

	//
	// initialize
	//
	void LogManager::initialize(wchar_t const* fileNameBase, uint32_t logLevel, bool useSysLog)
	{
		mLogFileNameBase													= fileNameBase;
		mLogLevel															= logLevel;

	#ifndef WIN32
		mSyslog																= useSysLog;
		if(mSyslog)
			openlog("u2daemon", LOG_PID | LOG_CONS, LOG_DAEMON);
	#endif
	}

	//
	// log message
	//
	void LogManager::logMessage(uint32_t logLevel, wchar_t const* format, ...) throw ()
	{
		va_list argList;
		va_start(argList, format);
		wchar_t messageBuffer[4096]											= {0};
		platform::vsnwprintf(messageBuffer, ARRAYSIZE(messageBuffer), format, argList);
		Utf8String utf8Message												= wideToUtf8(messageBuffer);

	#ifdef WIN32
		if(IsDebuggerPresent())
		{
			OutputDebugStringW(messageBuffer);
			OutputDebugStringW(L"\n");
		}
	#endif

		if(logLevel < mLogLevel)
			return;

	#ifndef WIN32
		if(mSyslog)
			return syslog(logLevel == LevelDebug ? LOG_DEBUG : (logLevel == LevelInfo ? LOG_INFO : (logLevel == LevelWarning ? LOG_WARNING : LOG_ERR)), "%s", utf8Message.c_str());
	#endif

		utils::Locker locker(mMutex);
		tm nowTm															= platform::getLocalTime(time(nullptr));
		if(nowTm.tm_hour != mLastLogTime.tm_hour || !mLogFile.isValid())
		{
			wchar_t fileName[64]											= {0};
			platform::snwprintf(fileName, ARRAYSIZE(fileName), (mLogFileNameBase + L".%04d-%02d-%02d_%02d.log").c_str(), nowTm.tm_year + 1900, nowTm.tm_mon + 1, nowTm.tm_mday, nowTm.tm_hour);
			mLogFile.openFile(fileName, L"at+");
			mLastLogTime													= nowTm;
		}

		if(!mLogFile.isValid())
			return;

		fprintf(mLogFile.getFile(), "[%04d-%02d-%02d %02d:%02d:%02d] %s\n", nowTm.tm_year + 1900, nowTm.tm_mon + 1, nowTm.tm_mday, nowTm.tm_hour, nowTm.tm_min, nowTm.tm_sec, utf8Message.c_str());
		fflush(mLogFile.getFile());
	}
}
